<template>
  <el-dialog
    :title="title"
    :visible.sync="isVisible"
    :width="width"
    :before-close="handleClose"
    :lock-scroll="true"
    :close-on-click-modal="false"
    custom-class="pub_dialog"
    @open="getData"
  >
    <VForm
      ref="vformComponents"
      :form="formData.form"
      :options="formData.options"
      :rules="formData.rules"
      :labelWidth="formData.labelWidth"
      :rowspan="rowspan"
      @toLoadMethods="toLoadMethods"
    ></VForm>

    <div class="formTitle-root">
      <div class="form-title-p">巡查项内容</div>
    </div>

    <div>
      <el-table :data="patrolModelItemList" border>
        <el-table-column
          prop="sort"
          label="序号"
          width="50"
        ></el-table-column>
        <el-table-column prop="itemType" label="*栏目名称">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.itemType"
              allow-create
              filterable
              default-first-option
              placeholder="栏目名称"
              @change="itemTypeChange"
              :disabled = "openType=='detail'"
            >
              <el-option
                v-for="item in itemTypeName"
                :key="item.key"
                :label="item.label"
                :value="item.label"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="itemName" label="*巡查项名称">
          <template slot-scope="scope">
            <el-input
              type="text"
              v-model="scope.row.itemName"
              placeholder="巡查项名称"
              :disabled = "openType=='detail'"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="rectifyDeadline" label="*整改期限">
          <template slot-scope="scope">
            <el-input
              type="text"
              v-model="scope.row.rectifyDeadline"
              placeholder="整改期限"
              :disabled = "openType=='detail'"
            ><i slot="suffix" style="font-style:normal;margin-right: 10px; line-height: 38px; color: #1e1e1e">天</i></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="itemName" label="*隐患等级">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.hazardLevel"
              filterable
              placeholder="隐患等级"
              :disabled = "openType=='detail'"
            >
              <el-option
                v-for="item in patrolHazardLevelOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="100"
          v-if="openType!='detail'"
        >
          <template slot-scope="scope">
            <i style="margin-right: 10px; cursor: pointer"
              class="el-icon-top toUpDown"
              @click="toUp(scope)"
              title="上移"
            ></i>
            <i style="margin-right: 10px; cursor: pointer"
              class="el-icon-bottom toUpDown"
              @click="toDown(scope)"
              title="下移"
            ></i>
            <span
              @click="deleteItem(scope)"
              style="cursor: pointer; color: red"
            >删除</span
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin-top:20px; float: right"  v-if="openType!='detail'">
      <el-button
        icon="el-icon-circle-plus-outline"
        type="primary"
        plain
        style="float: left;"
        size="small"
        @click="addPatrolModelItem"
      >添加巡查项</el-button>
    </div>

    <span slot="footer" class="dialog-footer">
     <el-button @click="cancel">{{openType!='detail' ? '取 消':'返 回'}}</el-button>
     <el-button type="primary" @click="sure" v-if="openType!='detail'">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import {
    patrolModelDetail,
    patrolModelUpdate,
    patrolModelAdd
  } from '@/api/risk/patrol'
  import {
    getInstitutionList
  } from '@/api/system/institution'
  import {
    getDeptList,getUserList
  } from '@/api/risk/dept'
  import { treeDataChild } from '@/api/risk/treeData'
  import VForm from "@/components/VForm/index";
  import { collectBuildingProjectList } from '@/api/build/project'
  export default {
    components: {
      VForm,
    },
    props: {
      width: {
        type: String,
        default: "80%",
      },
      title: {
        type: String,
        default: "详情",
      },
      id:{},
      openType:{
        type:String,
        default:"add"
      },
      dialogVisible: {
        type: Boolean,
        default: false
      },
      bClassifyOptions:{},
      modelTypeOptions:{}
    },
    watch: {
      'width': {
        handler(newVal, oldVal) {
          let w = this.width.split('%')[0]
          if(w>=60){
            this.rowspan = 2
          }else{
            this.rowspan = 1
          }
        },
        deep: true,
        immediate: true
      },
      'bClassifyOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='busiLargeType'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'modelTypeOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='modelType'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'sClassifyOptionsForm':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='busiSmallType'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'formData.form.busiLargeType':{
        handler(newVal, oldVal) {
          this.watchChangeLargeType()
        },
        deep: true,
        immediate: true
      },
      'belongUnitIdList':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='belongUnitId'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
      'openType':{
        handler(newVal, oldVal) {
          // 判断是否详情，添加不可编辑标识
          this.formData.options.forEach(t=>{
            t.disabled = newVal=='detail' ? true : false
          })
        },
        deep: true,
        immediate: true
      },
      'formData.form.modelType':{
        handler(newVal, oldVal) {
           this.formData.options.forEach(t=>{
             console.log("监听=====》",t)
             if(t.key=='belongUnitId'){
               t.disabled = newVal==1
             }
           })
          if(newVal == 1){
            this.formData.form.belongUnitId=''
          }
        },
        deep: true,
        immediate: true
      },
      'buildingIdOptions':{
        handler(newVal, oldVal) {
          this.formData.options.forEach(t=>{
            if(t.key=='buildingId'){
              t.option.data = newVal
            }
          })
        },
        deep: true,
        immediate: true
      },
    },
    computed: {
      isVisible: {
        get() {
          return this.dialogVisible
        },
        set() {
          this.close()
        }
      }
    },
    data() {
      return {
        patrolModelItemList:[],
        rowspan:1,
        dict:{},
        formData: {
          form: {
            id:"",
            modelName:"",
            modelType:"",
            busiLargeType:"",
            busiSmallType:"",
            remark:"",
            belongUnitId:[],
            buildingId:"",
          },
          options: [
            {
              title: "所属工地",
              key: "buildingId",
              type: "select",
              multiple:false,
              option: {
                data: this.buildingIdOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "projectName", // 指定label对应data的字段
                  value: "id", // 指定value对应data的字段
                },
              },
            },
            {
              title: "表单名称",
              key: "modelName",
              type: "text",
            },
            {
              title: "模板类型",
              key: "modelType",
              type: "select",
              multiple:false,
              option: {
                data: this.modelTypeOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "value", // 指定value对应data的字段
                },
              },
            },
            {
              title: "业务专题大类",
              key: "busiLargeType",
              type: "select",
              multiple:false,
              event: 'changeLargeType',
              option: {
                data: this.bClassifyOptions,
                props: {
                  key: "id", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "name", // 指定value对应data的字段
                },
              },
            },
            {
              title: "业务专题细类",
              key: "busiSmallType",
              type: "select",
              multiple:false,
              option: {
                data: this.sClassifyOptionsForm,
                props: {
                  key: "code", // 指定key对应data的字段
                  label: "label", // 指定label对应data的字段
                  value: "code", // 指定value对应data的字段
                },
              },
            },
            // {
            //   title: "所属单位",
            //   key: "belongUnitId",
            //   type: "select",
            //   multiple:true,
            //   option: {
            //     data: this.belongUnitIdList,
            //     props: {
            //       key: "id", // 指定key对应data的字段
            //       label: "name", // 指定label对应data的字段
            //       value: "id", // 指定value对应data的字段
            //     },
            //   },
            // },
            {
              title: "表单描述",
              key: "remark",
              type: "textarea",
              columnWidth: 'w100max',
            },
          ],
          rules: {
            modelName :[
              { required: true, message: '请输入', trigger: 'blur' },
              {max:64, message: '长度最大为24个字符', trigger: 'blur'}
            ],
            modelType :[
              { required: true, message: '请选择', trigger: 'change' },
            ],
            busiLargeType :[
              { required: true, message: '请选择', trigger: 'change' },
            ],
            busiSmallType :[
              { required: true, message: '请选择', trigger: 'change' },
            ],
            remark :[
              {max:256, message: '长度最大为256个字符', trigger: 'blur'}
            ],
          },
          labelWidth: "140px",
        },
        // 字典
        belongUnitIdList:[],
        sClassifyOptionsForm:[],
        patrolHazardLevelOptions:[],
        itemTypeName:[],
        belongUnitTempDataList:[],
        buildingIdOptions:[],
      };
    },
    methods: {
      addPatrolModelItem(){
        let item = {
          sort: this.patrolModelItemList.length + 1,
          itemType: "",
          itemName: "",
          rectifyDeadline:"",
          hazardLevel: "",
        };
        this.patrolModelItemList.push(item);
      },
      toUp(scope) {
        let index = scope.$index;
        if (index == 0) {
          return;
        }
        let tempList = this.patrolModelItemList;
        let preIndex = index - 1;
        let temp = this.patrolModelItemList[index];
        temp.sort = index;
        let preTemp = this.patrolModelItemList[preIndex];
        preTemp.sort = index + 1;
        tempList.splice(index, 1, preTemp);
        tempList.splice(preIndex, 1, temp);
        this.patrolModelItemList = tempList;
      },
      toDown(scope) {
        let index = scope.$index;
        if (index + 1 == this.patrolModelItemList.length) {
          return;
        }
        let tempList = this.patrolModelItemList;
        let afterIndex = index + 1;
        let temp = this.patrolModelItemList[index];
        temp.sort = afterIndex + 1;
        let afterTemp = this.patrolModelItemList[afterIndex];
        afterTemp.sort = afterIndex;
        tempList.splice(index, 1, afterTemp);
        tempList.splice(afterIndex, 1, temp);
        this.patrolModelItemList = tempList;
      },
      deleteItem(scope) {
        console.log(scope);
        let list = this.patrolModelItemList;
        let filterList = list.filter((t) => {
          return t.sort != scope.row.sort;
        });
        let index = 1;
        filterList.forEach((t) => {
          (t.sort = index), index++;
        });
        this.patrolModelItemList = filterList;
      },
      noBlank(val) {
        if (val != "" && val != null && val != undefined) {
          return true;
        }
        return false;
      },
      itemTypeChange(){
        let list = [
          ...new Set(
            this.patrolModelItemList
              .filter((t) => {
                return this.noBlank(t.itemType);
              })
              .map((t) => {
                return t.itemType;
              })
          ),
        ];
        this.itemTypeName = list.map((t) => {
          return { key: t, label: t };
        });
      },
      toLoadMethods(methods) {
        this[methods]()
      },
      watchChangeLargeType(){
        let queryData ={}
        queryData.name='hazardBClassify';
        queryData.code =this.formData.form.busiLargeType
        treeDataChild(queryData).then(res=>{
          if(res.code==200) {
            this.sClassifyOptionsForm = res.data
          }
        })
      },
      changeLargeType(){
        this.formData.form.busiSmallType = ''
      },
      initData(){
          this.formData.form.id = "",
          this.formData.form.modelName = "",
          this.formData.form.modelType = "",
          this.formData.form.busiLargeType = "",
          this.formData.form.busiSmallType = "",
          this.formData.form.remark = ""
          this.formData.form.belongUnitId=[]
          this.itemTypeName = []
          this.sClassifyOptionsForm = []
          this.patrolModelItemList= []
          this.belongUnitIdList = []
      },
      patrolModelItemListValid(){
        if(this.patrolModelItemList.length==0){
            return false;
        }
        let flag = true;
        this.patrolModelItemList.forEach(t=>{
          if(!this.noBlank(t.itemType) || !this.noBlank(t.itemName)
            || !this.noBlank(t.rectifyDeadline) || !this.noBlank(t.hazardLevel)){
            flag = false;
          }
        })
        return flag;
      },
      sure(){
        console.log('sure===',this.formData.form)
        this.$refs.vformComponents.$refs.form.validate().then(res=>{
          // 校验巡查内容
          if(!this.patrolModelItemListValid()){
            this.$message.warning("请完善巡查项内容！")
            return
          }
          let patrolModelBelongList = []
          if(this.formData.form.belongUnitId){
            this.formData.form.belongUnitId.forEach(t=>{
              let item  = this.belongUnitIdList.find(x=> x.id == t)
              if(undefined!= item){
                patrolModelBelongList.push({belongUnit: item.name, belongUnitId:item.id});
              }
            })
          }
          let tempParam = {
             ...this.formData.form,
             patrolModelItemList:this.patrolModelItemList,
             patrolModelBelongList:patrolModelBelongList
          }
          if(this.openType == "add" || this.openType == "likeAdd"){
            this.add(tempParam)
          }else{
            this.update(tempParam)
          }
        })
      },
      add(tempParam){
          tempParam.id = null
          patrolModelAdd(tempParam).then(res=>{
          if(res.code==200){
            this.$message({
              message: this.$t('tips.createSuccess'),
              type: 'success'
            })
            this.closeSuccess()
          }else{
            this.$message({
              message: res.message,
              type: 'error'
            })
          }
        })
      },
      update(tempParam){
        patrolModelUpdate(this.formData.form.id, tempParam).then(res=>{
          if(res.code==200){
            this.$message({
              message: this.$t('tips.updateSuccess'),
              type: 'success'
            })
            this.closeSuccess()
          }else{
            this.$message({
              message: res.message,
              type: 'error'
            })
          }
        })
      },
      cancel(){
        this.close()
      },
      handleClose(done) {
        done()
        this.close()
      },
      closeSuccess(){
        this.initData()
        this.$refs.vformComponents.$refs.form.resetFields();
        this.$emit('success')
      },
      close(){
        this.initData()
        this.$refs.vformComponents.$refs.form.resetFields();
        this.$emit('close')
      },
      getUnitListData(){
        console.log("this.$store.state.account.user===>",this.$store.state.account.user)
        let deptId = this.$store.state.account.user.deptId
        if(deptId){
          // // 区单位查询对应 （查询下级单位）
          // if(this.$store.state.account.user.deptIds.length<=4){
          //   getInstitutionList({fatherUnitId: deptId}).then(res=>{
          //       if(res.code==200){
          //         this.belongUnitIdList = res.data.map(t=>{ return {id:t.unitId, name:t.unitName} })
          //       }
          //   })
          // }else {
          //   // 可能区单位信息（仅查询对应本单位）
          //   getInstitutionList({unitId: deptId}).then(res=>{
          //     if(res.code==200){
          //       this.belongUnitIdList = res.data.map(t=>{ return {id:t.unitId, name:t.unitName} })
          //     }
          //   })
          // }

          getDeptList({deptId: deptId}).then(res=>{
            if(res.code==200){
              this.belongUnitIdList = res.data.map(t=>{ return {id:t.deptId, name:t.deptName} })
            }
          })

        }
        //  this.belongUnitIdList = [{id:"1",name:"天河区政府"},{id:"2",name:"海珠区政府"}]
      },

      getBuildProjectList(){
        collectBuildingProjectList().then(res=>{
          if(res.code==200){
            this.buildingIdOptions = res.data
            console.log("......",this.buildingIdOptions);
          }
        })
      },

      getData(){
          this.patrolHazardLevelOptions=[],
          this.$commonJs.filterDataDict("patrolHazardLevel",this.patrolHazardLevelOptions)
          this.getUnitListData()
        this.getBuildProjectList();
        if(this.openType!="add"){
          patrolModelDetail(this.id).then(res=>{
            if(res.code==200){
              this.formData.form = res.data
              this.patrolModelItemList = res.data.patrolModelItemList
              let temp = res.data.patrolModelBelongList.map(t=>{return t.belongUnitId})
              this.$set(this.formData.form,"belongUnitId", temp)
            }else{
              this.$message({
                message: this.$t('tips.systemException'),
                type: 'error'
              })
            }
          })
        }
      }
    },
  };
</script>

<style lang="scss" scoped>
  @import "@/styles/element-variables.scss";
  .formTitle-root{
    padding: 10px 0;
    border-bottom: 1px solid #EFEFEF;
    font-size: 16px;
    position: relative;
    margin-bottom: 10px;
    .form-title-p{
      padding-left: 10px;
      border-left: 4px solid $--color-primary;
    }
  }
  /*修改禁用样式*/
  ::v-deep .is-disabled .el-input__inner  {
    background-color:white;
    /*color: rgb(0, 0, 0);*/
  }
  ::v-deep .el-radio__input.is-disabled.is-checked .el-radio__inner{
    border-color: $--color-primary;
    background: $--color-primary;
  }
  ::v-deep .el-radio__input.is-disabled + span.el-radio__label{
    color: rgb(0, 0, 0);
  }
  ::v-deep .el-textarea.is-disabled .el-textarea__inner{
    background: white;
    color: rgb(0, 0, 0);
  }
</style>
